<!-- 用户管理-用户列表 -->
<template>
  <div class="app-container">
    <div class="searchbox">
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-form
            :inline="false"
            label-position="right"
            label-width="80px"
            :model="formInline"
            class="demo-form-inline"
          >
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="5">
              <el-form-item label="岗位名称:">
                <el-input v-model="formInline.title" clearable placeholder="请输入岗位名称" />
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="24" :md="8" :lg="12" :xl="14" style="text-align: right">
              <el-button size="small" @click="resetForm">重置</el-button>
              <el-button size="small" type="primary" :loading="searchLoad" @click="handleSearch">查询</el-button>
            </el-col>
          </el-form>
        </el-row>
      </el-card>
    </div>
    <div style="margin-top: 20px; display: flex; justify-content: flex-end">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="newConfirm">添加岗位</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      tooltip-effect="dark"
      :data="list"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="部门" width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.depart||'--' }}
        </template>

      </el-table-column>
      <el-table-column label="岗位名称" width="300">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column label="关联表单名称" width="300">
        <template slot-scope="scope">{{ scope.row.formTitle }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="300">
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column label="修改时间" width="300">
        <template slot-scope="scope">{{ scope.row.updateTime }}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button type="success" size="mini" width="100" @click="operation(scope.row, scope.$index)">编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            width="100"
            @click="operation_del(scope.row, scope.$index)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--   分页区 -->
    <div class="paging_device">
      <el-pagination
        :current-page="pages.current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pages.size"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pages.totalElements"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 弹出区域  认证 -->
    <el-dialog
      title="用户认证"
      :visible.sync="gradeChangeDialog"
      :close-on-click-modal="false"
      width="20%"
      class="dialog"
      :before-close="handleClose"
    >
      <div class="gradeChangeTitle">姓名：{{ userName }}</div>
      <div class="gradeChangeTitle">手机号：{{ phone }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="refuse">拒绝</el-button>
        <el-button type="primary" size="small" @click="pass">通过</el-button>
      </span>
    </el-dialog>
    <!-- 添加 编辑   弹窗-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addUserDialog"
      :close-on-click-modal="false"
      width="30%"
      class="dialog"
      :before-close="handleCloseAddUser"
    >
      <el-form
        ref="NewruleForm"
        :model="NewruleForm"
        :rules="rules"
        status-icon
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="岗位名称: " prop="postTitle">
          <el-input v-model="NewruleForm.postTitle" type="text" autocomplete="off" style="width: 70%" />
        </el-form-item>
        <el-form-item label="部门: " prop="departmentName">
          <el-cascader
            ref="cascader"
            v-model="NewruleForm.departmentName"
            :show-all-levels="false"
            style="width: 70%"
            :options="departmentOptions"
            :props="props"
            clearable
            filterable
          />
        </el-form-item>

        <el-form-item label="表单名称: " prop="formName">
          <el-select v-model="NewruleForm.formName" placeholder="请选择" style="width: 70%" filterable>
            <el-option v-for="item in formOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="establishIsNo('NewruleForm')">取消</el-button>
        <el-button type="primary" @click="establish('NewruleForm')">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        editId: '', // 编辑Id
        dialogTitle: '添加岗位',
        addUserDialog: false, // 添加编辑弹层开关
        NewruleForm: {
          postTitle: '', // 岗位名称
          departmentName: [], // 部门名称
          formName: '' // 表单名称
        },
        rules: {
          postTitle: [{
              required: true,
              message: '请输入岗位名称',
              trigger: 'blur'
            }

          ],
          departmentName: [{
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }],
          formName: [{
            required: true,
            message: '请选择表单名称',
            trigger: 'change'
          }]

        },
        formOptions: [], // 表单列表
        departmentOptions: [], // 部门数组
        props: {
          multiple: true,
          emitPath: false
        },
        IndustryQualification: '',

        searchLoad: false,
        formInline: {
          title: ''
        },
        loading: true,
        list: [],

        title: '',
        value: null,
        values: {
          formId: '',
          id: ''
        },

        input1: '',
        userName: '', // 等级变更记录 name
        isForbidden: [],
        grade_form: {
          userLevel: ['1'], // 弹出框-等级-多选框状态
          description: '' // 弹出框-备注-model
        },
        tableData: [{
          commentTimeFormat: '2020-03-27 14:19:34',
          roleName: '超级管理员',
          userLevel: '一级',
          postscript: '/'
        }],
        listLoading: false, // 列表加载状态
        multipleSelection: [], // 表单选中的数据
        pages: {
          current: 1, // 当前页
          totalElements: 0, // 总条数
          size: 10 // 每页条数
        },
        gradeDialog: false, // 等级设置 状态
        gradeChangeDialog: false, // 等级变更记录 状态
        phone: '', // 手机号
        userId: '', // 认证所需id

        // ----------------------------------------

        isabled: true, // 顶部禁用按钮  show state
        newlyAdded: { // 弹出 表单绑定值
          name: '',
          password: '默认密码:hkts1234', //  用户默认密码
          phone: '',
          department: '', //  部门
          distribution: '',
          station: '', // 岗位
          optionItem: '',
          id: null // id
        },
        notEmpty: { // 弹出 表单验证条件
          name: '',
          phone: ''
        },
        dialogFormVisible: false, // 弹出框状态

        // ------- 编辑弹窗  数据
        optionHidd: false,
        optionData: [],
        defaultProps: {
          children: 'childrenDepartment',
          label: 'title'
        },
        //     角色分配
        options: [],
        value1: [],
        value2: [],
        optionsArr: []

      }
    },
    watch: {
      value(newVal, oldVal) {
        console.log(newVal, oldVal)
      },
      addUserDialog(newVal) {
        if (newVal === false) {
          this.$refs['NewruleForm'].resetFields()
        }
      }
    },
    mounted() {},
    created() {
      this.hontPostGetByCondition()
      this.hkFormEntityGetAllList() // 获取表单名称数组
      this.getDepartmentList() // 部门
    },
    methods: {

      // 递归
      recursion(item) {
        if (item.childrenDepartment != null) {
          item.children = item.childrenDepartment
          if (item.children.length > 0) {
            item.value = item.id
            item.label = item.title
            item.children.forEach(ff => {
              this.recursion(ff)
            })
          } else {
            item.value = item.id
            item.label = item.title
            item.children = []
          }
        } else {
          item.value = item.id
          item.label = item.title
          item.childrenDepartment = []
        }
      },
      // 获取部门树
      async getDepartmentList() {
        try {
          const res = await this.$Http.getdDepartment()
          if (res.code === 200) {
            this.departmentOptions = res.result
            this.departmentOptions.forEach((item) => {
              this.recursion(item)
            })
          } else {
            this.$message({
              type: 'error',
              message: res.messsage
            })
            this.departmentOptions = []
          }
        } catch (error) {
          console.log('error', error)
        }
      },
      // 获取表单列表
      async hkFormEntityGetAllList() {
        try {
          const res = await this.$Http.hkFormEntityGetAllList()
          if (res.code === 200) {
            if (res.result.length > 0) {
              res.result.forEach(item => {
                this.formOptions.push({
                  value: item.id,
                  label: item.formName
                })
              })
            } else {
              this.formOptions = []
            }
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } catch (err) {
          console.log('err', err)
        }
      },

      // 重置
      resetForm() {
        this.formInline = this.$options.data().formInline
      },
      handleSearch() {
        this.pages.currten = 1
        this.hontPostGetByCondition()
      },

      // 分页请求接口
      hontPostGetByCondition(e) {
        const page = {
          current: this.pages.current,
          size: this.pages.size
        }
        const data = Object.assign({}, page, this.formInline)
        this.searchLoad = true
        this.$Http.hontPostGetByCondition(data).then(res => {
          this.searchLoad = false
          if (res.code === 200) {
            this.list = res.result.content
            this.pages.totalElements = res.result.totalElements
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        })
      },
      optionfn(value) {
        this.values.formId = value
      },
      // 每页条数
      handleSizeChange(val) {
        this.pages.size = val
        this.hontPostGetByCondition()
      },
      // 当前页
      handleCurrentChange(val) {
        this.pages.current = val
        this.hontPostGetByCondition()
      },

      // 取消添加 编辑
      establishIsNo(formName) {
        this.addUserDialog = false
        this.$refs[formName].resetFields()
      },
      //  添加岗位
      establish(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('new', this.NewruleForm)
            if (this.dialogTitle === '添加岗位') {
              const departmentList = []
              this.NewruleForm.departmentName.forEach((item) => {
                departmentList.push({
                  hontDepartmentId: item
                })
              })
              const params = {
                title: this.NewruleForm.postTitle,
                hontDepartmentPosts: departmentList,
                formId: this.NewruleForm.formName
              }

              this.$Http.hontPostGetByConditionSave(JSON.stringify(params)).then(res => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.message
                  })

                  this.addUserDialog = false
                  this.$refs['NewruleForm'].resetFields()
                  this.hontPostGetByCondition()
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
              }).catch(err => {
                console.log('err', err)
              })
            } else if (this.dialogTitle === '编辑岗位') {
              const departmentList = []
              this.NewruleForm.departmentName.forEach((item) => {
                departmentList.push({
                  hontDepartmentId: item
                })
              })

              const params = {
                id: this.editId,
                title: this.NewruleForm.postTitle,
                hontDepartmentPosts: departmentList,
                formId: this.NewruleForm.formName
              }
              this.$Http.xbootHontPostEdit(JSON.stringify(params)).then(res => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.message
                  })
                  this.addUserDialog = false
                  this.$refs['NewruleForm'].resetFields()
                  this.hontPostGetByCondition()
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
              }).catch(err => {
                console.log('err', err)
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 编辑
      operation(data, index) {
        this.dialogTitle = '编辑岗位'
        this.editId = data.id
        this.getEdit(this.editId)
      },
      // 编辑请求
      async getEdit(id) {
        try {
          const res = await this.$Http.getEditObj({
            postId: id
          })
          if (res.code === 200) {
            this.NewruleForm.departmentName = res.result.hontDepartmentPostIds
            this.NewruleForm.postTitle = res.result.title
            this.NewruleForm.formName = res.result.formId
            this.addUserDialog = true
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } catch (err) {
          console.log('err', err)
        }
      },
      // 删除
      operation_del(data, index) {
        // console.log(data)
        this.$Http.xbootHontPostDel({
          id: data.id
        }).then(res => {
          this.$message.success('删除成功')
          // console.log("删除成功")
          this.hontPostGetByCondition()
        })
      },

      //   编辑按钮  弹窗   树形结构数据方法
      handleNodeClick(data) {
        this.newlyAdded.optionItem = data.title
        this.NewruleForm.department = data.title
        this.NewruleForm.departmentid = data.id
      },
      // 编辑按钮里的   树形选项数据
      departmentTree() {
        this.$Http.departmentTree().then(res => {
          this.optionData = res.result
        })
      },
      // 岗位列表
      getAllList() {
        this.$Http.getAllList().then(res => {
          // console.log(res)
          res.result.forEach((item, index) => {
            this.options.push({
              id: item.id,
              label: item.title
            })
          })
        })
      },
      // 角色分配
      hontRole() {
        this.$Http.hontRole().then(res => {
          // console.log(res)
          res.result.forEach((item, index) => {
            this.optionsArr.push({
              id: item.id,
              label: item.name
            })
          })
        })
      },
      //  顶部  添加岗位
      newConfirm() {
        this.dialogTitle = '添加岗位'
        this.addUserDialog = true
      },
      // 分页请求接口
      // 头部搜索
      searchContent() {
        // console.log("搜索")
        this.$Http.personnelList({
          pageNumber: this.pages.current,
          pageSize: this.pages.size,
          nickName: this.input1
        }).then(res => {
          this.list = []
          this.list = res.result.content
        })
      },
      // 禁用状态
      switch_change(e) {
        this.$confirm('此操作将改变禁用状态, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            if (this.list[e].status === false || this.list[e].status === -1) {
              this.list[e].status = -1
            } else {
              this.list[e].status = 0
            }
            this.$Http
              .visitor_disable({
                userId: this.list[e].id,
                statu: this.list[e].status * 1
              })
              .then(res => {
                if (this.list[e].status === -1) {
                  this.$message({
                    type: 'success',
                    message: '已禁用！'
                  })
                  this.isForbidden[e] = '取消禁用'
                  this.list[e].status = false
                } else {
                  this.$message({
                    type: 'success',
                    message: '已取消禁用！'
                  })
                  this.isForbidden[e] = '点击禁用'
                  this.list[e].status = true
                }
              })
          })
          .catch(() => {
            this.visitor_getByDepartmentId()
          })
      },

      // 认证
      authentication(i) {
        this.userName = this.list[i].nickName
        this.phone = this.list[i].mobile
        this.userId = this.list[i].id
        this.gradeChangeDialog = true
      },
      // 认证通过
      pass(is, a, text) {
        this.$Http.user_authentication({
          userId: this.userId,
          approve: a || 1
        }).then(res => {
          this.gradeChangeDialog = false
          this.$message({
            message: text || '认证成功',
            type: 'success'
          })
          this.visitor_getByDepartmentId()
        })
      },
      // 拒绝认证
      refuse() {
        this.pass(null, 2, '已拒绝')
      },
      //     添加用户        创建按钮

      handleCloseAddUser() {
        this.addUserDialog = false
      },
      // 取消弹窗
      handleClose(done) {
        const that = this
        this.$confirm('确认关闭？')
          .then(_ => {
            that.gradeDialog = false
            this.gradeChangeDialog = false
          })
          .catch(_ => {})
      },
      // 表格选中状态
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (val.length > 0) {
          this.isabled = false
          val.forEach(item => {
            console.log(item)
          })
        } else {
          this.isabled = true
        }
      }

    }
  }
</script>
<style lang="scss" scoped>
  .app-container {
    padding: 0;
    margin: 20px;
  }

  .search_and_new {
    height: 5vh;
  }

  .search_and_new>div {
    display: inline-block;
    margin-right: 15px;
  }

  .paging_device {
    margin-top: 30px;
    text-align: center;
  }

  .gradeChangeTitle {
    font-size: 15px;
    margin-bottom: 20px;
    padding-left: 40px;
  }

  .dialog ::v-deep .el-dialog__footer {
    text-align: center;
  }
</style>

